<template>
  <div class="app-container">
    <div class="container">
      <a-card>
        <a-spin
          :spinning="progressing"
          :tip="progressingTips||'处理中...'"
        >
          <div class="button-bar">
            <a-button
              type="primary"
              :disabled="type=='view'|| !selectedData.id|| selectedData.level=='2'|| selectedData.level=='3'|| selectedData.level=='1' || type=='approve'"
              @click="addRow"
            >
              新增同级节点
            </a-button>
            <a-button
              type="primary"
              :disabled="type=='view'|| !selectedData.id
                || type=='approve'|| selectedData.level=='2'
                || selectedData.level=='3'
                || selectedData.level=='1'
                || selectedData.editable =='true'
                || selectedData.nodeStatusCode=='2'
                || selectedData.nodeStatusCode=='3'
                || selectedData.nodeStatusCode=='4'
                || !isEdit "
              @click="editAdjust('adjust')"
            >
              {{ selectedData.adjustCode == '1' ? '修改新增' : '信息调整' }}
            </a-button>
            <a-button
              type="default"
              :disabled="type=='view'
                || type=='approve'
                || !selectedData.id
                || selectedData.type==='add'
                || selectedData.level=='2'
                || selectedData.level=='3'
                || selectedData.level=='1'
                || selectedData.editable =='true'
                || selectedData.nodeStatusCode=='2'
                || selectedData.nodeStatusCode=='3'
                || selectedData.nodeStatusCode=='4'
                || !isEdit"
              :loading="loading"
              @click="editDelete('deleteNodes')"
            >
              删除
            </a-button>
            <a-button
              type="primary"
              @click="showDrawer()"
            >
              查看甘特图
            </a-button>
          </div>
          <div class="gantt-layout">
            <a-drawer
              ref="ganttDrawer"
              title=""
              placement="right"
              :closable="false"
              :z-index="10"
              :get-container="false"
              :visible="visible"
              :body-style="{padding:'0'}"
              :wrap-style="{ position: 'absolute'}"
              width="70%"
              :after-visible-change="afterVisibleChange"
              @close="onClose"
            >
              <gantt
                ref="ganttCom"
                class="left-container"
                :columns="ganttColumns"
                :plugins="plugins"
                :tasks="tasks"
                :heigh="ganttHeight"
                @task-deleted="deleteTask"
                @task-updated="logTaskUpdate"
                @link-updated="logLinkUpdate"
                @task-addModal="addModal"
                @task-selected="selectTask"
              />
            </a-drawer>

            <div class="pub-table-select-count">
              <a-icon
                type="info-circle"
                theme="twoTone"
              />
              <span style="margin-right: 12px">
                项目：<span class="totalNum">{{ total.projectName }} </span> |
                预调整节点共 ：<span class="totalNum">{{ total.adjusTotalNum || 0 }} 项 </span> |
                预调整一级节点共：<span class="totalNum">{{ total.adjustFirstNodeNum || 0 }} 项 </span> |
                预调整二级节点共：<span class="totalNum">{{ total.adjustSecondNodeNum || 0 }} 项 </span> |
                预调整三级节点共：<span class="totalNum">{{ total.adjustThirdNodeNum || 0 }} 项 </span>
              </span>
            </div>

            <ux-grid
              ref="bigDataTable"
              show-header-overflow
              show-body-overflow
              :height="600"
              :row-height="50"
              row-key
              row-id="id"
              :tree-config="{
                children: 'children',
                expandAll: false,
              }"
              :use-virtual="true"
              :border="false"
              :row-class-name="rowClassNames"
              @row-click="handleClickRow"
            >
              <ux-table-column
                v-for="item in columns"
                :key="item.id"
                :field="item.dataIndex"
                :title="item.title"
                :width="item.width"
                :tree-node="item.dataIndex === 'name'"
                align="center"
              >
                <template v-slot="{ row }">
                  <div
                    v-if="item.scopedSlots"
                    :title="row[item.dataIndex]"
                  >
                    <!-- 序号 -->
                    <div
                      v-if="item.dataIndex === 'sortNum'"
                      class="table-form-box"
                    >
                      <!--<span>{{row.sortNum}}</span>-->
                      <div style="text-align:center">
                        <div
                          v-if="row.statusLights == '0'"
                          style="text-align:right;padding:0 10px;display:flex;justify-content:space-between;direction:rtl; "
                        >
                          <div>{{ row.sortNum }}</div>
                          <div v-if="row.colorfulFlags=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/blueFlag.png"
                            >
                          </div>
                          <div v-if="row.colorfulFlags=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/greenFlag.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/yellowLight.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/redLight.png"
                            >
                          </div>
                        </div>
                        <div
                          v-if="row.statusLights == '1'"
                          style="text-align:right;padding:0 10px;display:flex;justify-content:space-between;direction:rtl;background: rgba(224, 244, 223, 1); "
                        >
                          <div>{{ row.sortNum }}</div>
                          <div v-if="row.colorfulFlags=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/blueFlag.png"
                            >
                          </div>
                          <div v-if="row.colorfulFlags=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/greenFlag.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/yellowLight.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/redLight.png"
                            >
                          </div>
                        </div>
                        <div
                          v-if="row.statusLights == '2'"
                          style="text-align:right;padding:0 10px;display:flex;justify-content:space-between;direction:rtl;background: rgba(251, 230, 232, 1); "
                        >
                          <div>{{ row.sortNum }}</div>
                          <div v-if="row.colorfulFlags=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/blueFlag.png"
                            >
                          </div>
                          <div v-if="row.colorfulFlags=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/greenFlag.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/yellowLight.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/redLight.png"
                            >
                          </div>
                        </div>
                        <div
                          v-if="row.statusLights == '3'"
                          style="text-align:center;background: rgba(240, 153, 164, 1);padding:0 10px;display:flex;justify-content:space-between;direction:rtl;"
                        >
                          <div>{{ row.sortNum }}</div>
                          <div v-if="row.colorfulFlags=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/blueFlag.png"
                            >
                          </div>
                          <div v-if="row.colorfulFlags=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/greenFlag.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='1'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/yellowLight.png"
                            >
                          </div>
                          <div v-if="row.promptLights=='2'">
                            <img
                              style="width:20px"
                              src="../../../assets/icons/redLight.png"
                            >
                          </div>
                        </div>
                        <div
                          v-if="row.statusLights!='0'&& row.statusLights!='1'&& row.statusLights!='2'&& row.statusLights!='3'"
                          style="padding:0 10px;display:flex;justify-content:space-between;direction:rtl;"
                        >
                          {{ row.sortNum }}
                        </div>
                      </div>
                      <!-- </template> -->
                    </div>
                    <!--阶段/类别-->
                    <div
                      v-if="item.dataIndex === 'name'"
                      class="table-form-box"
                    >
                      <span> {{ row.name }}</span>
                    </div>
                    <!--业务事项-->
                    <div
                      v-if="item.dataIndex === 'businessMatters'"
                      class="table-form-box"
                    >
                      <BaseTextarea
                        v-if="row.editable=='true' && (parseInt(row.id)<=1000||row.adjustCode=='1' || allowProjectUpdateColumn)"
                        v-model="row.businessMatters"
                        placeholder="请输入"
                        :auto-size="{minRows: 2, maxRows: 2}"
                        :show-limit-tip="false"
                        :show-stretch="false"
                        @change="changeMatter"
                      />
                      <span v-else>{{ row.businessMatters }}</span>
                    </div>
                    <!-- 管控级别 -->
                    <div
                      v-if="item.dataIndex === 'controlLevelName'"
                      class="table-form-box"
                    >
                      <a-select
                        v-if="((row.editable=='true' && row.level=='4' && adjustTypes=='adjust')|| parseInt(row.id)<=1000 || row.type=='add')&& row.type!='deleteNodes'"
                        v-model="row.controlLevelName"
                        :get-popup-container="getPopupContainer"
                        style="width:100px;height:28px"
                        @change="(value)=>changeLevel(row,value)"
                      >
                        <a-select-option
                          v-for="item in nodeList"
                          :key="item.controlLevelId"
                        >
                          {{ item.controlLevelName }}
                        </a-select-option>
                      </a-select>
                      <template v-else>
                        {{ row.controlLevelName }}
                      </template>
                    </div>
                    <!-- 周期 -->
                    <div
                      v-if="item.dataIndex === 'duration'"
                      class="table-form-box"
                    >
                      <BaseInputNumber
                        v-if="((row.editable=='true' && row.level=='4' && adjustTypes=='adjust') || parseInt(row.id)<=1000)&& row.type!='deleteNodes' "
                        v-model="row.duration"
                        placeholder="请输入"
                        :min="0"
                        :max="2000"
                        @change="editduration(row)"
                      />
                      <span v-else>{{ row.duration }}</span>
                    </div>
                    <!-- 计划开始时间 -->
                    <div
                      v-if="item.dataIndex === 'startTime'"
                      class="table-form-box"
                    >
                      <a-date-picker
                        v-if="((row.editable=='true' && row.level=='4' && adjustTypes=='adjust') || parseInt(row.id)<=1000) && row.type!='deleteNodes' "
                        v-model="row.startTime"
                        placeholder="请输入"
                        style="width:120px"
                        @change="(date)=>editstartTime(row,date)"
                      />
                      <span v-else>{{ row.startTime }}</span>
                    </div>
                    <!-- 计划完成时间 -->
                    <div
                      v-if="item.dataIndex === 'endTime'"
                      class="table-form-box"
                    >
                      <span>{{ row.endTime }}</span>
                    </div>
                    <!-- 实际完成时间 -->
                    <div
                      v-if="item.dataIndex === 'completeTime'"
                      class="table-form-box"
                    >
                      <span>{{ row.completeTime }}</span>
                    </div>
                    <!--            完成标准-->
                    <div v-if="item.dataIndex === 'completeStandard'">
                      <div class="table-form-box">
                        <BaseTextarea
                          v-if="row.editable=='true' && (parseInt(row.id)<=1000||row.adjustCode=='1' || allowProjectUpdateColumn) && row.type!='deleteNodes'"
                          v-model="row.completeStandard"
                          placeholder="请输入"
                          :auto-size="{minRows: 2, maxRows: 2}"
                          :show-limit-tip="false"
                          :show-stretch="false"
                          @blur="changecompleteStandard"
                        />
                        <span v-else>{{ row.completeStandard }}</span>
                      </div>
                    </div>
                    <!-- 验证资料 -->
                    <div
                      v-if="item.dataIndex === 'verifyDoc'"
                      class="table-form-box"
                    >
                      <BaseTextarea
                        v-if="row.editable=='true' && (parseInt(row.id)<=1000||row.adjustCode=='1' || allowProjectUpdateColumn) && row.type!='deleteNodes'"
                        v-model="row.verifyDoc"
                        placeholder="请输入"
                        :auto-size="{minRows: 2, maxRows: 2}"
                        :show-limit-tip="false"
                        :show-stretch="false"
                        @blur="changeverifyDoc"
                      />
                      <span v-else>{{ row.verifyDoc }}</span>
                    </div>
                    <!-- 第一责任人 -->
                    <div
                      v-if="item.dataIndex === 'firstResponsibleName'"
                      class="table-form-box"
                    >
                      <template v-if="row.editable=='true' && adjustTypes=='adjust'&&(parseInt(row.id)<=1000 || row.adjustCode=='1' || allowProjectUpdateColumn) && row.type!='deleteNodes'">
                        <a @click="handleBind(row)"> {{ row.firstResponsibleName ? `重新选择(${row.firstResponsibleName})` : '选择第一责任人' }}</a>
                      </template>
                      <span v-else>
                        {{ row.firstResponsibleName }}
                      </span>
                    </div>
                    <!-- 直接责任人 -->
                    <div
                      v-if="item.dataIndex === 'responsibleName'"
                      class="table-form-box"
                    >
                      <a-select
                        v-if="((row.editable=='true' && row.level=='4' && adjustTypes=='adjust') || parseInt(row.id)<=1000 ) && row.type!='deleteNodes' "
                        v-model="row.responsible"
                        :get-popup-container="getPopupContainer"
                        label-in-value
                        @change="changeRespons"
                      >
                        <a-spin
                          v-if="loading"
                          slot="notFoundContent"
                          size="small"
                        />
                        <a-select-option
                          v-for="item in responsLists"
                          :key="item.employeeId"
                          :value="item.employeeId"
                        >
                          {{ item.employeeName }}
                        </a-select-option>
                      </a-select>
                      <template v-else>
                        {{ row.responsibleName }}
                      </template>
                    </div>
                  </div>
                  <span
                    v-else
                    :title="row[item.dataIndex]"
                  >
                    {{ row[item.dataIndex] }}
                  </span>
                </template>
              </ux-table-column>
              <ux-table-column
                fixed="right"
                width="220"
                title="操作"
              >
                <template v-slot="{ row }">
                  <span v-if="row.editable == 'true' || (parseInt(row.id) <= 1000)">
                    <a
                      v-if="row.type=='add'"
                      @click="() => saveAdd(row)"
                    >保存新增</a>
                    <a
                      v-if="row.type=='adjust'"
                      @click="() => saveAdjust(row)"
                    >{{ row.adjustCode == '1' ? '保存修改' : '保存调整' }}</a>
                    <a
                      v-if="row.type=='deleteNodes'"
                      @click="saveDelete(row)"
                    >保存删除</a>
                    <a-divider type="vertical" />
                    <a @click="cancelEditRecord(row)">取消</a>
                  </span>
                  <a-divider
                    v-if="row.level=='4'&&(row.editable == 'true' || (parseInt(row.id) <= 1000))"
                    type="vertical"
                  />
                  <a
                    v-if="row.level=='4'&&row.childrenAdjust&&row.childrenAdjust.length>0"
                    @click="showMoreList(row)"
                  >更多</a>
                </template>
              </ux-table-column>
            </ux-grid>
          </div>
          <modal
            :id="currentId"
            :org-query="orgQuery"
            :screening="screening"
            :visible="bindOrgVisible"
            @handleCancelFirstRes="handleCancelFirstRes"
            @job-selected="handleOk"
          />
        </a-spin>
      </a-card>
    </div>
    <MoreList
      :visible="showMoreListVisible"
      :more-list-data="moreListData"
      @closeMoreList="closeMoreList"
    />
  </div>
</template>
<script>
import { gantt } from 'dhtmlx-gantt'
import { getProjects } from '@/api/construction/planInput'
import {
  getWbsTemplate,
  addSameNode,
  addNextNode,
  editNode,
  deleteNode,
  editTemplateNode,
  getNodeControl
} from '@/api/template'
import Gantt from '../gantt/gantt'
// import TaskTemplateModal from '../gantt/template-modal'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
// import * as moment from 'moment'
// import EditableCell from './EditableCell'
import { getOrgPost } from '@/api/commons'
import { getPreAdjustDetail, addNode, deleteWork, editeWork, adjustWorks } from '@/api/adjust'
import { getOrganizeUserList } from '@/api/commons'
import indexVue from '@/components/TitleName/index.vue'
import modal from '@/components/SelectJobs' // 第一责任人
import moment from 'moment'
import Vue from 'vue'
import MoreList from '../adjust/list/moreListModal.vue'
import { UxGrid, UxTableColumn } from 'umy-ui'

const columns = [
  {
    title: '序号',
    width: '70px',
    align: 'center',
    dataIndex: 'sortNum',
    scopedSlots: { customRender: 'sortNum' }
  },
  {
    title: '阶段/类别',
    dataIndex: 'name',
    align: 'left',
    ellipsis: true,
    scopedSlots: { customRender: 'name' },
    width: 160
  },
  {
    title: '业务事项',
    dataIndex: 'businessMatters',
    width: 130,
    ellipsis: true,
    scopedSlots: { customRender: 'businessMatters' }
  },
  {
    title: '管控级别',
    align: 'center',
    dataIndex: 'controlLevelName',
    scopedSlots: { customRender: 'controlLevelName' },
    width: 120
  },
  {
    title: '周期',
    dataIndex: 'duration',
    align: 'center',
    width: 120,
    scopedSlots: { customRender: 'duration' }
  },
  {
    title: '计划开始时间',
    dataIndex: 'startTime',
    align: 'center',
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: 'startTime' }
  },
  {
    title: '计划完成时间',
    dataIndex: 'endTime',
    align: 'center',
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: 'endTime' }
  },
  // {
  //   title: '前置任务',
  //   dataIndex: 'completeTime',
  //   align:'center',
  //   width: 120,
  //   scopedSlots: { customRender: 'completeTime' },
  // },
  // {
  //   title: '间隔时间',
  //   dataIndex: 'completeTime',
  //   align:'center',
  //   width: 120,
  //   scopedSlots: { customRender: 'completeTime' },
  // },
  {
    title: '实际完成时间',
    dataIndex: 'completeTime',
    align: 'center',
    width: 120,
    ellipsis: true,
    scopedSlots: { customRender: 'completeTime' }
  },
  {
    title: '完成标准',
    dataIndex: 'completeStandard',
    width: 200,
    align: 'center',
    ellipsis: true,
    scopedSlots: { customRender: 'completeStandard' }
  },
  {
    title: '验证资料',
    dataIndex: 'verifyDoc',
    align: 'center',
    ellipsis: true,
    width:200,
    scopedSlots: { customRender: 'verifyDoc' }
  },
  {
    title: '第一责任人',
    align: 'center',
    dataIndex: 'firstResponsibleName',
    width: 150,
    ellipsis: true,
    scopedSlots: { customRender: 'firstResponsibleName' }
  },
  {
    title: '直接责任人',
    width: 150,
    align: 'center',
    ellipsis: true,
    dataIndex: 'responsibleName',
    scopedSlots: { customRender: 'responsibleName' }
  },
  {
    title: '节点状态',
    align: 'center',
    width: 120,
    dataIndex: 'nodeStatus'
  },
  {
    title: '调整情况',
    width: 120,
    align: 'center',
    dataIndex: 'adjustInformation'
  }
  /*{
    title: '操作',
    width: 220,
    align:'center',
    dataIndex: 'action',
    fixed:'right',
    scopedSlots: { customRender: 'action' },
  },*/
]

export default {
  props: {'adjustPlanId':[String,Number]},
  name: 'DhtmlxGantt',
  components: { Gantt, modal, MoreList, UxGrid, UxTableColumn },
  data() {
    return {
      isGanttDataOk: false,
      ganttData: { data: [] },
      levelOption: '',
      isEdit: true,
      progressing: false,
      progressingTips: '处理中...',
      showMoreListVisible: false,
      tableData: [],
      startDates: '',
      scrollTop: 0,
      selectedData: {},
      loading: false,
      locale,
      cancelList: '',
      selectParentId: '',
      total: {},
      tasks: { data: [], links: [] },
      columns,
      templateId: '',
      screening: true,
      addLevel: '',
      moreListData: [],
      ganttHeight: 661,
      cacheData: '',
      orgQuery: {},
      resultData: {},
      saveSelectRows: [],
      ganttColumns: [],
      firstResponsible: [],
      endTime: '',
      bindOrgVisible: false,
      currentId: '',
      selectNodeLevel: '',
      disabled: false,
      startTime: '',
      preTasks: [],
      editable: false,
      projectId: '',
      selectLevel: '',
      taskType: 'task',
      responsLists: [],
      modalTitle: '新增节点',
      confirmLoading: false,
      responsibleId: '',
      responsibleName: '',
      nodeList: '',
      selectResponsible: {},
      addVisible: false,
      visible: false,
      selectId: '',
      type: '',
      adjustTypes: '',
      editingKey: '',
      taskTemplateVisible: false,
      plugins: {
        undo: true,
        drag_timeline: true
      },
      messages: [],
      selectedTask: null,
      rangeConfig: {
        rules: [{ type: 'array', required: true, message: '请选择计划日期!' }]
      },
      today: '2020-11-20',
      firstResponsibleData:{}
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, {})
  },
  watch: {
    tableData(list) {
      if (this.$refs.bigDataTable) {
        // 获取之前展开数据
        const expandRecords = this.$refs.bigDataTable.getTreeExpandRecords()
        const scrollTop = this.$refs.bigDataTable.tableExample().getScroll().scrollTop
        // 获取之前滚动高度
        // 加载数据
        this.$refs.bigDataTable.reloadData(list).then(() => {
          // 数据加载完成出现之后，打开之前的展开行
          const expandKeys = expandRecords.map(item => item.id)
          const needExpandRecords = []
          // 遍历tree，找到需要展开的数据，再依次展开
          const deepFn = (list) => {
            list && list.forEach(item => {
              if (expandKeys.includes(item.id)) {
                needExpandRecords.push(item)
              }
              item.children && deepFn(item.children)
            })
          }
          deepFn(this.tableData)
          needExpandRecords.forEach(row => {
            this.$refs.bigDataTable.setTreeExpand(row, true)
          })
          // 还原之前滚动高度
          this.$nextTick(() => {
            this.$refs.bigDataTable.pagingScrollTopLeft(scrollTop)
          })
        })
      }
    }
  },
  computed: {
    allowProjectUpdateColumn() {
      try {
        const allowList = JSON.parse(sessionStorage.getItem('allowProjectList'))
        return allowList.includes(this.projectId)
      } catch {
        return false
      }
    }
  },
  created() {
    this.today = moment().format('yyyy-MM-DD')
    const userInfo = Vue.getAcloudProvider().getUserInfo()
    this.currentId = userInfo.id
    this.planId = this.$route.query.id
    this.type = this.$route.query.type
    this.getPreAdjustDetail(true)
    if (this.$route.fullPath == '/construction/addAdjustViews') {
      this.type = 'view'
    }
    localStorage.removeItem('task')
    localStorage.removeItem('link')
    this.tasks.data = []
    this.tasks.links = []
    this.ganttColumns = [
      {
        name: 'sortNum', label: '编号', align: 'center', resize: true, tree: false, width: 40, template: function(obj) {
          return obj.$index + 1
        }
      },
      {
        name: 'name', label: '阶段/类别', align: 'left', resize: true, tree: false, width: 140, template: function(obj) {
          return obj.text
        }
      }
    ]
    gantt.config.layout = {
      css: 'gantt_container',
      cols: [
        {
          min_width: 140,
          width: 140,
          rows: [
            { view: 'grid', scrollX: 'gridScroll', scrollable: true, scrollY: 'scrollVer' },
            { view: 'scrollbar', id: 'gridScroll', group: 'horizontal' }
          ]
        },
        { resizer: true, width: 1 },
        {
          rows: [
            { view: 'timeline', scrollX: 'scrollHor', scrollY: 'scrollVer' },
            { view: 'scrollbar', id: 'scrollHor', group: 'horizontal' }
          ]
        },
        { view: 'scrollbar', id: 'scrollVer' }
      ]
    }
    gantt.config.date_format = '%Y-%m-%d'
    const cfg = gantt.config
    const strToDate = gantt.date.str_to_date(cfg.date_format, cfg.server_utc)
    gantt.templates.parse_date = function (date) {
      return strToDate(date)
    }
  },
  methods: {
    // 更多
    showMoreList(record) {
      this.showMoreListVisible = true
      this.moreListData = record.childrenAdjust
    },
    // 关闭更多弹窗
    closeMoreList() {
      this.showMoreListVisible = false
    },
    // 第一责任人
    handleCancelBindOrg(val) {
      // this.bindOrgVisible=val
    },
    handleCancelFirstRes() {
      this.bindOrgVisible = false
    },
    handleBind(record) {
      this.bindOrgVisible = true
      this.firstResponsibleData = record
    },
    handleOk(value) {
      this.bindOrgVisible = false
      this.firstResponsibleData.firstResponsibleName = value.name
      this.firstResponsibleData.firstResponsibleId = value.id
      this.firstResponsibleData.firstResId = value.id
    },
    // 直接责任人查询
    getOrganizePeopleList() {
      this.loading = true
      getOrganizeUserList({ id: this.projectId }).then(res => {
        this.responsLists = res.data
        this.loading = false
      })
    },
    // 获取当前是否有数据在调整或修改
    isAdjustEditable(){
      this.tableData.forEach(item1 => {
        if (item1.children) {
          item1.children.forEach(item2 => {
            if (item2.children) {
              item2.children.forEach(item3 => {
                if (item3.children) {
                  item3.children.forEach(item4 => {
                    if (item4.editable == 'true') {
                      this.isEdit = false
                      return false
                    }
                  })
                }
              })
            }
          })
        }
      })
      if (!this.isEdit) {
        this.$message.error('请先保存当前预调整')
        return false
      }
      return true
    },
    editAdjust(type) {
      this.cancelList = { ...this.selectedData }
      const isEditable = this.isAdjustEditable()
      if(!isEditable){
        return
      }
      this.selectedData.type = 'adjust'
      this.adjustTypes = type
      if (this.selectedData.level == '1' ||
        this.selectedData.level == '2' ||
        this.selectedData.level == '3') {
        if (type == 'adjust') {
          this.$message.error('不可调整')
        } else if (type == 'del') {
          this.$message.error('不可删除')
        }
      } else {
        const newData = [...this.tableData]
        this.selectedData.editable = 'true'
        this.tableData = newData
        if (type == 'adjust') {
          this.selectResponsible = {
            key: this.selectedData.responsibleId,
            label: this.selectedData.responsibleName
          }
        }
      }
    },
    // 保存新增
    saveAdd(record) {
      if (!record.businessMatters) {
        this.$message.warning('请填写业务事项信息！')
        return
      }
      if (!record.controlLevelName) {
        this.$message.warning('请选择管控级别！')
        return
      }
      if (this.$isEmpty(record.duration)) {
        this.$message.warning('请填写周期！')
        return
      }
      if (!record.startTime) {
        this.$message.warning('请填写选择开始时间！')
        return
      }
      if (!record.completeStandard) {
        this.$message.warning('请填写完成标准！')
        return
      }
      if (!record.verifyDoc) {
        this.$message.warning('请填写验证资料！')
        return
      }
      if (!record.firstResponsibleName) {
        this.$message.warning('请选择第一责任人！')
        return
      }
      if (!record.responsible) {
        this.$message.warning('请选择直接责任人！')
        return
      }
      record.responsibleName = record.responsible.label
      if (record.responsible) {
        record.responsibleName = record.responsible.label
        record.responsibleId = record.responsible.key
      }
      record.controlLevelId = record.controlLevelName
      record.planId = this.planId
      record.adjustType = '0'
      // 判断每项必填
      if (record.businessMatters && record.businessMatters !== ''
        && record.controlLevelName && record.controlLevelName !== ''
        && !this.$isEmpty(record.duration)
        && record.startTime && record.startTime !== ''
        && record.completeStandard
        && record.completeStandard !== ''
        && record.verifyDoc && record.verifyDoc !== ''
        && record.firstResponsibleName && record.firstResponsibleName !== ''
        && record.responsibleName && record.responsibleName !== '') {
        this.progressing = true
        addNode(record).then(res => {
          this.progressing = false
          this.getPreAdjustDetail(true)
          if (res.code == '200') {
            this.selectedData.editable = 'false'
            record.editable = 'false'
            this.$message.success('新增成功')
          }
        }).catch(() => {
          this.progressing = false
        })
      } else {
        this.$message.error('请将信息填写完整再保存')
      }

    },
    // 保存调整
    saveAdjust(record) {
      record.adjustType = '0'
      record.planId = this.planId
      if (record.responsible) {
        record.responsibleName = record.responsible.label
        record.responsibleId = record.responsible.key
      }
      record.firstResId = this.selectedData.firstResponsibleId
      record.firstResponsibleId = this.selectedData.firstResponsibleId
      if (!record.controlLevelName) {
        this.$message.warning('请选择管控级别！')
        return
      }
      if (this.$isEmpty(record.duration)) {
        this.$message.warning('请填写周期！')
        return
      }
      if (!record.startTime) {
        this.$message.warning('请填写选择开始时间！')
        return
      }
      //新增节点信息修改
      if (record.adjustCode == '1') {
        record.isAdjustAdd = '1'
        record.oldWorkId = record.id
        if (!record.businessMatters) {
          this.$message.warning('请填写业务事项信息！')
          return
        }
        if (!record.completeStandard) {
          this.$message.warning('请填写完成标准！')
          return
        }
        if (!record.verifyDoc) {
          this.$message.warning('请填写验证资料！')
          return
        }
        if (!record.firstResponsibleName) {
          this.$message.warning('请选择第一责任人！')
          return
        }
      }
      if (!record.responsibleName) {
        this.$message.warning('请选择直接责任人！')
        return
      }
      // record.controlLevelId = record.controlLevelName
      if (record.controlLevelName && record.controlLevelName !== ''
        && !this.$isEmpty(record.duration)
        && record.startTime && record.startTime !== ''
        && record.responsibleName && record.responsibleName !== '') {
        this.progressing = true
        editeWork(record).then(res => {
          this.getPreAdjustDetail(true)
          if (res.code == '200' || res.data.code == '200') {
            this.isEdit = true // 保存成功之后，重置状态
            this.selectedData.editable = 'false'
            record.editable = 'false'
            this.$message.success('保存成功')
          }
          this.progressing = false
        }).catch(()=>{
          this.progressing = false
        })
      } else {
        this.$message.error('请将信息填写完整再保存')
        return false
      }
    },
    editDelete(type) {
      const isEditable = this.isAdjustEditable()
      if(!isEditable){
        return
      }
      this.cancelList = { ...this.selectedData }
      if (!this.selectedData) {
        this.$message.warn('请先选择要删除的节点')
        return false
      } else if (this.selectedData.level == '1' || this.selectedData.level == '2' || this.selectedData.level == '3') {
        this.$message.error('不能删除')
        return false
      } else {
        this.selectedData.editable = 'true'
        this.selectedData.type = 'deleteNodes'
      }
    },
    // 保存删除
    saveDelete(record) {

      if (!this.selectedData) {
        this.$message.warn('请先选择要删除的节点')
        return false
      } else if (this.selectedData.level == '1' || this.selectedData.level == '2' || this.selectedData.level == '3') {
        this.$message.error('不能删除')
        return false
      } else {
        let _this = this
        this.$confirm({
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          title: '删除当前选择的节点?',
          onOk() {
            let data = {}
            data = {
              planId: _this.planId,
              parentId: _this.selectedData.parentId,
              adjustId: _this.selectedData.id,
              oldWorkId: _this.selectedData.oldWorkId,
              adjustType: '0',
              isAdjustAdd: _this.selectedData.isAdjustAdd,
              controlLevelId: record.controlLevelId
            }
            _this.progressing = true
            // debugger;
            deleteWork(data).then((res) => {
              _this.progressing = false
              if (res) {
                _this.getPreAdjustDetail()
              }
              if (res.code == '200') {
                _this.$message.success('节点删除成功')
              }
            }).catch(() => {
              _this.loading = false
              _this.progressing = false
            })
            // _this.$refs.ganttCom.action(name)
          },
          onCancel() {
          },
          class: 'test'
        })
      }
    },

    getProjects(id) {
      const params = {
        projectIds: [id]
      }
      getProjects(params).then((res) => {
        this.orgQuery.ids = res.data[0].orgId
      })
    },
    cancelEditRecord(record) {
      this.isEdit = true
      if (parseInt(record.id) <= 1000) {
        this.getPreAdjustDetail()
      } else {
        record.editable = 'false'
        this.selectedData.type = ''
        record.controlLevelId = this.cancelList.controlLevelId
        record.controlLevelName = this.cancelList.controlLevelName
        record.duration = this.cancelList.duration
        record.startTime = this.cancelList.startTime
        record.responsibleId = this.cancelList.responsibleId
        record.responsibleName = this.cancelList.responsibleName
      }
    },
    changeRespons(value) {
    },
    addRow() {
      if (!this.selectedData) {
        this.$message.error('请选择要新增的节点位置')
        return false
      } else if (this.selectedData.level == '1' || this.selectedData.level == '2' || this.selectedData.level == '3') {
        this.$message.error('此节点不可新增')
        return false
      } else {
        this.adjustTypes = 'adjust'
        this.selectParentId = this.selectedData.parentId
        let row = {
          name: '', businessMatters: '',
          level: 4, duration: '',
          startTime: '',
          oldWorkId: this.selectedData.oldWorkId || this.selectedData.id,
          completeTime: '', editable: 'true',
          completeStandard: '', type: 'add',
          firstResponsibleName: '', responsibleName: '',
          id: Math.floor((Math.random() * 1000) + 1)
        }

        let arr = []
        this.tableData.forEach(item => {
          if (item.children) {
            item.children.forEach(item2 => {
              if (item2.children) {
                item2.children.forEach((item3, index) => {
                  arr.push(item3)
                })
              }
            })
          }
        })
        let list = []
        // 筛选出选择的节点的父节点
        list = arr.filter(item => item.id === this.selectedData.parentId)
        const thisParent = list[0]
        if (!thisParent) {
          this.$message.warning('没有找到父级节点信息，请稍后重试！！')
          return
        }
        // 获取选中的元素在数组中的下标
        if (list[0].children) {
          let currentIndex = (list[0].children || []).findIndex((item) => item.id === this.selectedData.id)
          list[0].children.splice(parseInt(currentIndex) + 1, 0, row)
        }
        this.$message.success('点击每行后面的保存按钮进行保存信息！！')
        this.selectResponsible = {}
      }
    },

    getNodeControl() {
      getNodeControl().then((res) => {
        this.nodeList = res.data
      })
    },
    changeName(value) {
    },
    // 标准开始时间
    editstartTime(record, date) {
      this.startTime = date.format('yyyy-MM-DD')
      record.startTime = this.startTime
      if (record.duration) {
        const endDate = date.add(record.duration, 'd').format('yyyy-MM-DD')
        this.$set(record, 'endTime', endDate)
      }
    },
    // 周期
    editduration(record) {
      if (record.startTime) {
        const startTimeMom = moment(record.startTime, 'yyyy-MM-DD')
        const endDate = startTimeMom.add(record.duration, 'd').format('yyyy-MM-DD')
        this.$set(record, 'endTime', endDate)
      }
    },
    // 验证资料
    changeverifyDoc(e) {
      this.saveSelectRows.verifyDoc = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        verifyDoc: this.saveSelectRows.verifyDoc
      }
    },
    // 完成标准
    changecompleteStandard(e) {
      this.saveSelectRows.completeStandard = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        completeStandard: this.saveSelectRows.completeStandard
      }
    },
    // 管控节点
    changeLevel(record, value) {
      this.selectNodeLevel = value
      record.controlLevelId = value
    },
    // 计划完成时间
    editEndTime(value, dateString) {
      let data = {}
      this.endTime = dateString
    },
    // 业务事项
    onCellChangeBusiness(val) {
      this.selectedData.name = val
    },
    // 获取模板
    getPreAdjustDetail(showLoading) {
      if (showLoading) {
        this.progressing = true
        this.progressingTips = '加载中...'
      }
      if (!this.planId) {
        this.planId = this.adjustPlanId
      }
      if (this.planId) {
        getPreAdjustDetail({ planId: this.planId }).then((res) => {
          // debugger
          this.cacheData = JSON.parse(JSON.stringify(res.data.list))

          this.getProjects(res.data.projectId)
          this.tableData = []
          this.tableData = Object.assign([], res.data.list)
          this.tableData.forEach(item1 => {
            if (item1.children) {
              item1.children.forEach(item2 => {
                if (item2.children) {
                  item2.children.forEach(item3 => {
                    if (item3.children) {
                      item3.children.forEach(item4 => {
                        if (item4.responsibleId) {
                          const area = {
                            label: item4.responsibleName,
                            key: item4.responsibleId
                          }
                          this.selectResponsible = area
                          item4.responsible = area
                        }
                      })
                    }
                  })
                }
              })
            }
          })
          this.ganttData = this.buildGanttData(this.tableData, true)
          this.total = res.data
          console.log(this.total)
          this.projectId = res.data.projectId
          // 首次渲染时默认选择第一条
          // this.selectId = this.tableData[0].id
          // this.selectedData = this.tableData[0]
          this.getOrganizePeopleList()
          this.getNodeControl()
          this.progressing = false
          this.progressingTips = ''
        }).catch(() => {
          this.progressing = false
          this.progressingTips = ''
        })
      }
    },
    renderGantt() {
      if (this.isGanttDataOk) {
        return
      }
      gantt.clearAll()
      console.log(this.ganttData)
      gantt.parse(this.ganttData)
      this.isGanttDataOk = true
    },
    buildGanttData(treeData, open) {
      const ganttData = {
        data: [],
      }
      const readTreeData = (children, parent) => {
        children.forEach((c) => {
          // 这里后端返回的数据有问题，一级节点的parentId也有值，这会导致gantt图渲染错误，因此将一级节点的parentId置空
          const data = { ...c, id: c.id, type: c.children ? 'project' : '', parent, open, parentId: !parent ? '' : c.parentId }
          ganttData.data.push(this.valuesToTask(data))
          if (c.children && c.children.length > 0) {
            readTreeData(c.children, c.id, open)
          }
        })
      }
      readTreeData(treeData, null, open)
      return ganttData
    },
    // 保存阶段名称
    blurData(e, record) {
      this.saveSelectRows.name = e.target.value
      let data = {}
      if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
        data = {
          templateId: this.templateId,
          nodeId: this.selectedData.nodeId,
          parentId: this.selectedData.workPackId,
          workPackName: this.saveSelectRows.name

        }
      } else {
        data = {
          templateId: this.templateId,
          nodeId: this.selectedData.nodeId,
          name: this.saveSelectRows.name
        }
      }
    },
    changeMatter(e, record) {
      this.saveSelectRows.businessMatters = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        name: this.saveSelectRows.businessMatters
      }
    },
    /**
     * 控制umi-table的点击
     */
    handleClickRow(record) {
      this.selectId = record.id
      this.selectedData = record
      console.log('选中数据', record)
      this.rowClassNames(record)
      const isExists = gantt.isTaskExists(record.id)
      if(isExists){
        gantt.selectTask(record.id)
      }
    },
    onClose() {
      this.visible = false
    },
    showDrawer() {
      this.visible = !this.visible
      this.renderGantt()
    },
    afterVisibleChange(visible) {
      if (visible) {
        gantt.refreshData()
      }
    },
    rowExpand(expanded, task) {
      if (expanded) {
        gantt.open(task.id)
      } else {
        gantt.close(task.id)
      }
    },
    valuesToTask(values) {
      const _this = this
      return {
        id: values.id,
        parent: values.parentId,
        text: (values.name!=='-'&&values.name) || values.businessMatters,
        name: values.name,
        businessMatters: values.businessMatters,
        start_date: values.start_date || values.startTime || _this.today,
        startDate: values.startDate || values.startTime || _this.today,
        end_date: values.end_date || values.endTime || _this.today,
        endDate: values.endDate || values.endTime || _this.today,
        duration: values.duration,
        type: values.type,
        preTask: values.preTask,
        matters: values.businessMatters,
        levelType: values.levelType,
        responsible: values.responsible,
        firstResponsible: values.firstResponsible,
        level: values.level,
        open: values.open
      }
    },
    // 新增同级节点
    addNode() {
      let _this = this
      //如果选择的是一级二级三级节点
      if (_this.selectedData.level != '4') {
        this.$message.error('此节点不可新增节点')
        return false
      } else {
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定新增节点?',
          onOk() {
            addNode({
              parentId: _this.selectedData.parentId,
              planId: _this.planId,
              adjustType: '0'
            }).then(res => {
              if (res) {
                _this.getPreAdjustDetail()
              }
              if (res.code == 200) {
                _this.$message.success('新增成功')

              }
            })
          }
        })
      }
    },
    action(name) {
      let _this = this
      let task_id = gantt.getSelectedId()
      _this.$refs.ganttCom.action(name)

      // 删除节点
      if ('del' === name) {
        let task_id = gantt.getSelectedId()
        if (!this.selectedData) {
          this.$message.warn('请先选择要删除的节点')
          return false
        } else if (this.selectedData.level == '1' || this.selectedData.level == '2' || this.selectedData.level == '3') {
          this.$message.error('不能删除')
          return false
        } else if (parseInt(this.selectedData.id) <= 1000) {
          this.getPreAdjustDetail()
        } else {
          this.loading = true
          let _this = this
          this.$confirm({
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            title: '删除当前选择的节点?',
            onOk() {
              let data = {}
              data = {
                planId: _this.planId,
                parentId: _this.selectedData.parentId,
                adjustId: _this.selectedData.id,
                oldWorkId: _this.selectedData.oldWorkId,
                adjustType: '0',
                isAdjustAdd: _this.selectedData.isAdjustAdd,
                controlLevelId: _this.selectedData.controlLevelId
              }

              deleteWork(data).then((res) => {
                if (res) {
                  _this.getPreAdjustDetail()
                }
                if (res.code = '200') {
                  _this.loading = false
                  _this.$message.success('节点删除成功')
                }
              })
            },
            onCancel() {
              _this.loading = false
            },
            class: 'test'
          })
        }
      } else {
      }
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    selectTask: function(task) {
      this.selectedTask = task
    },
    deleteTask: function(taskId) {
      this.selectedTask = task
      gantt.deleteTask(task.id)
    },
    addMessage(message) {
      let _this = this
      _this.messages.unshift(message)
      if (_this.messages.length > 40) {
        _this.messages.pop()
      }
    },
    logTaskUpdate(id, mode, task) {
      const text = (task && task.text ? ` (${task.text})` : '')
      const message = `Task ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
    rowClassNames(record) {
      if (this.selectId == record.id) {
        return 'clickRowStyle'
      }
    },
    logLinkUpdate(id, mode, link) {
      let message = `Link ${mode}: ${id}`
      if (link) {
        message += ` ( source: ${link.source}, target: ${link.target} )`
      }
      this.addMessage(message)
    },
    addModal(task) {
      this.confirmLoading = false
      const tasks = gantt.getTaskByTime()
      let parent = gantt.getSelectedId()
      this.addVisible = true
    }

  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.table-form-box {
  height: 42px;
  line-height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;

  @{deep} textarea.ant-input {
    height: 42px !important;
    min-height: 42px !important;
    padding: 1px 10px;
  }
}
</style>
<style lang="less" scoped>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

/deep/ .ant-table-body .clickRowStyle {
  background-color: rgb(230, 243, 252);
}

/deep/ .ant-pro-basicLayout-children-content-wrap {
  flex: 1;
}

.gantt-layout {
  position: relative;
}

/deep/ .ant-table-thead th {
  height: 60px;
  line-height: 60px;
  padding: 0;
}

/deep/ .ant-table-placeholder {
  height: 600px;
}

/deep/ .gantt-layout .ant-table-body {
  min-height: 600px;
}

/deep/ .ant-drawer-content-wrapper {
  box-shadow: none !important;
}

/deep/ .ant-table-selection-column {
  width: 40px;
}

.button-bar {
  margin-bottom: 10px;
}

.button-bar > button:not(:first-child) {
  margin-left: 10px;
}

/deep/ .ant-modal-body {
  padding: 0
}

td {
  display: flex;
}

/* /deep/ .ant-select:not(.ant-pagination-options-size-changer) .ant-select-selection{
  height:100% !important;
  width:100px !important
} */

input[type='text'], input[type='password'], input[type='number'], textarea {
  width: 100%;
  height: 28px !important
}

.ant-calendar-picker {
  width: 200px;
  height: 28px
}

.ant-cascader-picker {
  width: 100%;
  height: 28px
}

form .ant-select, form .ant-cascader-picker {
  width: 100%;
  height: 28px !important
}

.ant-calendar-picker-input.ant-input {
  width: 200px;
  height: 28px !important
}

/deep/ .ant-card-bordered {
  margin-top: 0
}

/deep/ .ant-table-tbody > tr > td {
  padding: 10px !important;
}

/deep/ .elx-table.elx-editable .elx-body--column, .elx-table.elx-editable .elx-body--column.col--actived {
  padding: 10px 0 !important
}

/deep/ .ant-select-selection--single {
  height: 28px !important
}

/deep/ .elx-table .elx-body--column.col--ellipsis, .elx-table .elx-footer--column.col--ellipsis, .elx-table .elx-header--column.col--ellipsis, .elx-table.elx-editable .elx-body--column {
  height: 60px !important
}
/deep/ .ant-select-tree li span.ant-select-tree-switcher,
.ant-select-tree li span.ant-select-tree-iconEle{
  line-height: 12px !important;
}
</style>